package com.neusoft.yiyang.auth.controller;

import com.neusoft.yiyang.auth.service.AuthService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

// 类级别注解：描述控制器功能
@Tag(name = "认证接口", description = "用户登录、Token刷新、注销等认证相关操作")
@RestController
@RequestMapping("/authenticate")
public class AuthController {

    @Autowired
    private AuthService authService;

    @Operation(summary = "用户登录", description = "通过用户名、密码和验证码获取访问令牌（accessToken）和刷新令牌（refreshToken）")
    @PostMapping("/login")
    public Map<String, Object> login(
            @Parameter(description = "用户名", required = true) @RequestParam("username") String username,
            @Parameter(description = "密码", required = true) @RequestParam("password") String password,
            @Parameter(description = "验证码唯一标识（从获取验证码接口返回）", required = true) @RequestParam("captchaKey") String captchaKey,
            @Parameter(description = "用户输入的验证码", required = true) @RequestParam("inputCaptcha") String inputCaptcha) {
        Map<String, String> tokens = authService.login(username, password, captchaKey, inputCaptcha);
        return buildSuccessResult(tokens);
    }

    @Operation(summary = "刷新访问令牌", description = "使用刷新令牌（refreshToken）获取新的访问令牌")
    @PostMapping("/refresh-token")
    public Map<String, Object> refreshToken(
            @Parameter(description = "刷新令牌（登录时返回的refreshToken）", required = true) @RequestParam("refreshToken") String refreshToken) {
        Map<String, String> tokens = authService.refreshToken(refreshToken);
        return buildSuccessResult(tokens);
    }

    @Operation(summary = "用户注销", description = "注销当前用户，将访问令牌加入黑名单")
    @PostMapping("/logout")
    public Map<String, Object> logout(
            @Parameter(description = "访问令牌（accessToken）", required = true) @RequestParam("token") String token) {
        authService.logout(token);
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "注销成功");
        return result;
    }

    private Map<String, Object> buildSuccessResult(Object data) {
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("data", data);
        return result;
    }
}